package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.article.service.ApArticleService;
import com.heima.common.contants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleFreemarkerService apArticleFreemarkerService;

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {

        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);

        //文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        //2.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        //3.结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        return responseResult;
    }

    /**
     * 保存或修改文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) throws Exception {
        /*// 测试服务降级
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        // 1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.拷贝数据到pojo
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        // 3.判断参数中是否有id,没有为新增,有的话就是修改
        if (dto.getId() == null) {
            // 3.1.保存文章数据
            save(apArticle);
            // 保存文章配置
            ApArticleConfig articleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(articleConfig);

            // 保存文章内容
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(apArticle.getId());
            articleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(articleContent);
        } else {
            // 3.2.修改文章数据
            // 修改文章
            updateById(apArticle);
            // 修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers
                    .<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        // 异步调用,生成文章html页面
        apArticleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

        // 4.封装返回结果
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 修改文章上下架状态
     *
     * @param map
     */
    @Override
    public void updateEnable(Map map) throws Exception {
        long articleId = (long) map.get("id");
        boolean enable = (boolean) map.get("enable");

        // 1.查询文章配置
        ApArticleConfig apArticleConfig = apArticleConfigMapper
                .selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                        .eq(ApArticleConfig::getArticleId, articleId));

        // 2.修改文章上下架状态
        if (apArticleConfig != null){
            apArticleConfig.setIsDown(enable);
            apArticleConfigMapper.updateById(apArticleConfig);
        }

        // 3.上架则生成静态页面.下架则删除静态页面
            ApArticle article = getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, articleId));
        if (enable){
            // 当前操作为下架,删除minIO中的文件
            fileStorageService.delete(article.getStaticUrl());
        }else {
            // 当前操作为上架,生成文章的html文件
            ApArticleContent apArticleContent = apArticleContentMapper
                    .selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, articleId));
            apArticleFreemarkerService.buildArticleToMinIO(article,apArticleContent.getContent());
        }
    }


}
